import datetime
import time
import jqdatasdk
from django.http import JsonResponse
from django.shortcuts import render, redirect
from django.views.decorators.cache import cache_page

from django.contrib.auth import models as auth_models
from Library_WEB import settings
from stocksys import models as stocksys_models, tasks
from stocksys.sys_tasks.logic_function import get_realtime_stock_content
from stocksys.views.data_logic import resources2infojson, getResourceBySpider, get_market_index_json_info
from stocksys.views.user_views import check_login
from stocksys.views.views import init_message


@check_login
# @cache_page(60)
def market_index_list(request):
    context = init_message(request)
    context["title"] = "量化分析系统-大盘股指"
    _market_indexs = stocksys_models.MarketIndex.objects.all()
    user = auth_models.User.objects.get(id=request.session.get('id'))
    sysconf = stocksys_models.SysConf.objects.get(user=user)
    exchanges = []
    for exchange in _market_indexs:
        market_index_code = "%s%s" % (exchange.exchange_address.stock_sina_name, exchange.code)
        info = get_realtime_stock_content(market_index_code)
        exchange_chg = 0
        if info['current'] != 0:
            exchange_chg = (info['current'] - info['close']) / info['close']
        if exchange_chg < 0:
            color = 'success'
        elif exchange_chg == 0:
            color = 'warning'
        else:
            color = 'danger'
        exchanges.append({
            'name': exchange.name,
            'type': exchange.type,
            'abbreviated_name': exchange.abbreviated_name,
            'exchange_address': exchange.exchange_address,
            'code': exchange.code,

            'open': info['open'],
            'close': info['close'],
            'current': info['current'],
            'chg': exchange_chg * 100,
            'chg_price': exchange_chg,
            'color': color,
            'volume': info['v_num'] / 10000,
            'money': info['money'] / 10000,
            "systime": datetime.datetime.now().strftime('%Y-%m-%d'),
        })
    context["exchanges"] = exchanges
    context["now_year"] = int(time.strftime('%Y', time.localtime(time.time())))
    context["quant_start_date"] = sysconf.predict_start_time.strftime("%Y-%m-%d")
    context["quant_end_date"] = sysconf.predict_end_time.strftime("%Y-%m-%d")
    context["predict_type"] = 'market_index'

    context["spider_mode"] = False
    if settings.USE_JQDATA_SDK:
        context["spider_mode"] = True
    return render(request, "stocksys/table_list/exchange_table.html", context)


@check_login
def market_index_info(request, code, addr, year):
    print(code,addr)
    exchange_address=stocksys_models.ExchangeAddress.objects.get(id=addr)
    market_index = stocksys_models.MarketIndex.objects.get(code=str(code), exchange_address=exchange_address)
    if request.method == "GET":
        # TODO:单支大盘指数数据

        context = init_message(request)
        context["title"] = "量化分析系统-股指信息"
        context["market_index_address"] = market_index.exchange_address.stock_address_name
        context["market_index"] = market_index
        context["exchange_code"] = code
        context["exchange_addr"] = addr
        return render(request, "stocksys/info/mark_index_info.html", context)
    elif request.method == "POST":
        info = get_market_index_json_info(market_index)
        return JsonResponse(info)


@check_login
def market_index_time_info(request, code):
    # TODO:单支大盘指数数据
    return JsonResponse({"statue": 200, "page": "market_index_time_info"})
